package cxm.proj.xtalk;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import cxm.lib.util.MyLog;
import cxm.proj.xtalk.smack.UserManager;

public class TalkTextActivity extends Activity {
	Chat newChat = null;
	private String talkName = null;
    TextView textView = null;
	EditText editText = null;
	private String chatText = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_talktext);
		
		Bundle b = getIntent().getExtras();
		this.talkName = b.getString("name");
		MyLog.Log(MyLog.Level.Info, "Talk to " + this.talkName);
		
		this.textView = (TextView)this.findViewById(R.id.text_content);
		this.editText = (EditText)this.findViewById(R.id.edit_content);
		
		newChat = UserManager.getInstance().getUser().createChat(
				this.talkName, new MessageListener() {
		    public void processMessage(Chat chat, Message message) {
		        MyLog.Log(MyLog.Level.Info, "Received message: " + message);
		        chatText = message.getBody();
		        TalkTextActivity.this.runOnUiThread(new Runnable(){
		            public void run(){
				        textView.setText(textView.getText() + talkName +
				        		": " + chatText + "\n");
		            }
		        });
		    }
		});
	}
	
	@Override
	public void onResume() {
		super.onResume();
		this.textView.setText("");
	}
	
	public void onSendClicked(View view) {
		String sendText = editText.getText().toString();
		if ("" == sendText || null == sendText) {
			MyLog.Log(MyLog.Level.Warning, "Send empty text");
			return;
		}
		
		try {
		    newChat.sendMessage(sendText);
		    editText.setText("");
		    textView.setText(textView.getText() + "Self: " + sendText + "\n");
		}
		catch (XMPPException e) {
		    System.out.println("Error Delivering block");
		}
	}
}
